package com.atguigu.gmall.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * @author mgx
 * @version 1.0
 * @description: TODO
 * @date 2022/10/20 23:27
 */
@Configuration
public class CorsConfig {

    /**
     * 服务端统一跨域处理
     * @return
     */
    @Bean
    public CorsWebFilter corsWebFilter() {
        // 创建配置对象
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 配置允许所有的ip都可以访问
        corsConfiguration.addAllowedOrigin("*");
        // 设置是否从服务器获取cookie
        corsConfiguration.setAllowCredentials(true);
        // 配置允许所有请求头
        corsConfiguration.addAllowedHeader("*");
        // 配置允许访问方法
        corsConfiguration.addAllowedMethod("*");
        // 配置源对象
        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
        configurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsWebFilter(configurationSource);
    }
}
